import { defineStore } from 'pinia'
import { getUserInfo,getAllUserInfo,changeUserBaseInfo } from '@/api/userHttp'
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {
      id: '',
      openid: '',
      token: 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDYwMjE0NDMsInVzZXJJZCI6Mn0.zXNCgKKo_9exqjj8RB9C3dYwMxSewgYGcxVYIqqTim0'
    },
    userNextInfo:{},
    isLogin: false
  }),
  
  getters: {
    // 获取用户名
    getUserToken(){
      return this.userInfo.token
    },
    getUsername: (state) => state.userInfo.nickName || '未设置昵称'
  },
  
  actions: {
    // 获取用户信息
    async fetchUserInfo(code) {
      console.log(code);
      // return
      const {data:{data}} = await getUserInfo(code)
      this.userInfo = data
      this.getAllUserInfo(data.token)
      uni.setStorageSync('userInfo', this.userInfo)
      this.isLogin = true
      uni.setStorageSync('isLogin', this.isLogin)
    },
    async getAllUserInfo(token){
      const {data:{data}} = await getAllUserInfo(token)
      this.userNextInfo = data
      // console.log(this.userNextInfo);
    },
    // 退出登录
    logout() {
      this.userInfo = {}
      this.userNextInfo = {}
      this.isLogin = false
      uni.removeStorageSync('userInfo')
    },
    
    async changeUserBaseInfo(){
      const newUserNextInfo = {
          ...this.userNextInfo,
          sex: this.userNextInfo.sex === '男' ? '1' : '0'
      };
      await changeUserBaseInfo(newUserNextInfo,this.userInfo.token)
    }
    
  }
}) 